<template>
  <div class='box-wrap-wskt'>
    <div class="box-top">
      <div>
        <span>INS筛开通</span>
        <span>
          1.导出结果请根据需要导出不同格式。
        </span>
      </div>

    </div>
    <div class='box-operation'>
      <div class="box-search">       
                

        <div class='form-group-enquire'>
          <DatePicker type="daterange" placeholder="请选择时间" style="width: 190px" :editable=false  v-model="searchDate" @on-change="changeDate" @on-clear="initDate"></DatePicker>
        </div>
        <div class='form-group-enquire'><el-Input v-model.trim="searchData.warehouse_name" placeholder="请输入仓库名称" clearable style="width: 200px" @on-enter="onSearchGetList()"></el-Input></div>
        <div class='form-group-enquire'><el-Input v-model.trim="searchData.user_name" placeholder="请输入用户名称" clearable style="width: 200px" @on-enter="onSearchGetList()"></el-Input></div>
        <div class='form-group-enquire'>
          <el-select v-model="searchData.country_id" style="width:200px" placeholder="国家" clearable filterable :disabled="UserInfo.role=='商务'?true:false">
            <el-option :value=row.id v-for="row in countrylist" :label="row.name" :key=row.id ><span>{{row.name}}</span></el-option>
          </el-select>
        </div>    
        <div class='form-group-enquire' @click='onSearchGetList()'><img src="../../assets/images/peach-svg/Frame 23.svg" title="点击刷新"></div>  
        <div class="form-group-right-button">
          <div class='form-group-enquire'  @click='downloadFile()'><img src="../../assets/images/peach-svg/export_list.svg"></div>
          <div class='form-group-enquire'  @click='addSieveOpen2(2)'><img src="../../assets/images/peach-svg/export_pl.svg"></div>
          <div class='form-group-enquire' @click='addSieveOpen(1)'><img src="../../assets/images/peach-svg/yuan_list.svg"></div>
          <div class='form-group-enquire' @click='addSieveOpen(3)'><img src="../../assets/images/peach-svg/paic_export.svg"></div>
        </div>
      </div>
    </div>
    <LibVxeTable class="staticData"
      :tableColumns="tableColumns" 
      :tableData="list" 
      :slotHeader="slotHeader" 
      border="none"
      :PageObj="{total:totalCnt,currentPage:searchData.page_index,pageSize:searchData.page_size}"  
      @onPageChange="onChangePageSize" 
      @onSelectChange="onCheckChange"   
      :stripe="false"
      resizable>
     </LibVxeTable>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import utils from "../../commons/utils";
import {commonMixin} from "../../components/ViewInitMixin" //每一个文件都要包含这个
import {TimePicker} from "iview"
import SearchUser from "../searchUser"
import Request from "../../commons/Request"
import {ACDN} from "@/commons/staticName";
import bus from "@/commons/EventBus";

export default {
  name: "addUserDetailView",  //!!这块一定要注意，每一个文件都根据资源path来命名
  components:{TimePicker,SearchUser},
  mixins:[commonMixin],
  data() {
    return {
      searchDate:"",
      searchTime:[utils.dateFormat(0,"HH")+"00",utils.dateFormat(0,"HH")+"00"],
      searchData:{
        page_index:1,
        page_size:30,
        start:"",
        end:"",
        country_id:"",
        name:"",
        warehouse_name:"",
        user_name:""
      },
      time_at:"",
      time_mouth:"",
      selectRows:[],
      countrylist:[],
      sourcelist:[],
      countrylistObj:{},
      list:[],
      totalCnt:0,
      info:{},
      tableColumns:[
        { 
        field: "Id",
        type:"checkbox",
        align: "center",
        width:50,
        },
        {
          title: "用户名称",
          field: "user_name",
          align: 'center',
        },
        {
          title: "任务名称",
          field: "task_name",
          align: 'center',
        },
        {
          title: "仓库名称",
          field: "warehouse_name",
          align: 'center',
        },
        
        {
          title: "任务数",
          field: "task_number",
          align: 'center',
        },
        {
          title: "开通数",
          field: "valid_number",
          align: 'center',
        },
        {
          title: "国家",
          field: "country",
          // align: 'center',
          // slots: {
          //   default: ({row},h) => {
          //     let name = "";
          //       if(this.countrylistObj.hasOwnProperty(row.country_id)){
          //       name = this.countrylistObj[row.country_id];
          //       }
          //       return [h("div",name)]
          //   }
          // }
        },
        {
          title: "总消耗积分",
          field: "points_consume_total",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_total==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_total/10000)]
            }
          }
        }, 
        {
          title: "账户积分消耗",
          field: "points_consume_account",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_account==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_account/10000)]
            }
          }
        },
        {
          title: "赠送积分消耗",
          field: "points_consume_gift",
          align: 'center',
          slots:{
            default:({row},h) =>{
              if(row.points_consume_gift==0){
                return [h("div",'-')]
              }else
              return [h("div",row.points_consume_gift/10000)]
            }
          }
        },
        // {
        //   title: "利润",
        //   field: "profit",
        //   align: 'center',
        //   slots:{
        //     default:({row},h) =>{
        //       if(row.profit==0){
        //         return [h("div",'-')]
        //       }else
        //       return [h("div",row.profit/10000)]
        //     }
        //   }
        // },
        {
          title: "状态",
          field: "status",
          align: 'center',
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
                hButton.push(h(
                    "div",
                    {
                      class:row.status==1?"eight":row.status==2?"four":row.status==3?"five":row.status==4?"six":row.status==5?"seven":"seven",
                      // on: {
                      //   click: () => {
                      //     this.editInfo(2,row);
                      //   }
                      // }
                    },
                  ));
              return hButton;
            });
            }
          }
        },
        {
          title: "开始/完成时间",
          field: "start_time",
          align: 'center',
          width:  130,
          slots: {
            default: ({row},h) => {
                 return [h("div",(row.start_time==0?"--":utils.dateFormat(row.start_time, "yyyy-MM-dd HH:mm:ss"))
                 +"/"+(row.end_time==0?" --":utils.dateFormat(row.end_time, "yyyy-MM-dd HH:mm:ss")))];
            }
          }
        },
        {
          title: "耗时",
          field: "elapsed_time",
          align: 'center',
          slots: {
            default: ({row},h) => {
              return [h("div",row.elapsed_time==""?"--":row.elapsed_time)];
            }
          }
        },
        {
          title: "操作",
          field: "action",        
          align: "center",
          slots:{
            default: ({row},h) => {
              return this.$AutoFun(()=>{
              let hButton = [];
                hButton.push(
                  h(
                    "el-button",
                    {
                      props: { type: "success", size: "small" },
                      style: { marginRight: "5px" },
                      on: {
                        click: () => {
                          this.addWarehouse2(1,2,row.id);
                        }
                      }
                    },
                    "导出结果"
                  )
                );
              return hButton;
            });
            }
          }
        } 
      ],
      format: {  
        number_of_single:{
          labelName: "单文件数量",
          labelType: "text",      
          placeholder:"请输入单文件数量(最小值100个，最大值100w)",
          labelHide:false
        },
        export_format:{
          labelName: "导出格式",
          labelType: "radio",    
          labelValue:[{"key":2,"value":"CSV格式"},{"key":1,"value":"TXT格式"}], 
        },
        export_type:{
          labelName: "导出类型",
          labelType: "radio",    
          labelValue:[{"key":1,"value":"WS群发格式"},{"key":2,"value":"短信格式"}],     
        },   
        export_mode:{
          labelName: "导出方式",
          labelType: "radio",    
          labelValue:[{"key":2,"value":"全部导出"},{"key":1,"value":"分批导出"}], 
          labelChange:"export_mode"       
        },     
      },  
      ruleValidate: {
        // number_of_single: [{ required: true,message: "导出输量不能为空", trigger: "blur" }],
      }, 
      dateOptions:{
        disabledDate(date){
          return date && date.valueOf() > Date.now();
        },

      },
    };
  },
  computed: {
            ...mapGetters(["UserInfo"]),
        },
  methods: {  
    async initView(isMounted){
      if(isMounted){
        this.initSearchData();
        this.onSearchGetList()
      }
    },
    async initSearchData(){
      let res = await Request.post("exclude", "GetCountries");
      if (res.code == 0) {
        this.countrylistObj = {}
        this.countrylist = []
        if(res.code==0 && res.data != null){
            res.data.list.forEach((item) => {
            this.$set(this.countrylistObj,item.id,item.short_name+"_"+item.full_name)
            this.countrylist.push({id:item.id,name:item.short_name+"_"+item.full_name});
            })  
        }
      }
    },
    
    onSearchGetList(){
      this.searchData.page_index =1;
      this.getList();
    },
    async getList(){
      utils.showLoading()
      //查询
      let res = await this.RequestPost("query_list",this.searchData);
      if(res.code==0 && res.data != null){
        this.list = [];
        if(res.data.list!=null) this.list = res.data.list;
        this.totalCnt = res.data.total
        bus.$emit('monitor-sieve-list',this.list)
        // this.list.push({"totalName":"合计","Cnt":res.data.TotalUserCnt});
      }
      await utils.sleepMs(500)
      utils.hideLoading();
    },
    //文件下载
    async addWarehouse(type,row,rowid){
      
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "文件下载";
        info={
          ids:rowid,
          export_format:1,
          export_type:1,
          export_mode:2,
          number_of_single:"",
          file_type:row
        }
      }     
      this.onSelectChange("export_mode",info.export_mode);
      this.info=info
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,labelWidth:150,width:700,cancelBtnStatus:0},
        this.info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );      
    },
    //导出
    async addWarehouse2(type,row,rowid){
      
      this.handleType=type;
      let title = "";
      let info = {};
      if(this.handleType==1){
        title = "导出";
        info={
          ids:rowid,
          export_format:1,
          export_type:1,
          export_mode:2,
          number_of_single:"",
          file_type:row
        }
      }     
      this.onSelectChange("export_mode",info.export_mode);
      this.info=info
      this.formPopIndex=await utils.showFormPage(
        { title: title,el:this.$parent.$el,labelWidth:150,width:700,cancelBtnStatus:0},
        this.info,
        this.format,
        this.ruleValidate,
        this.updateInfo,
        this.onSelectChange,
      );      
    },
    onCheckChange(rows){
        this.selectRows = [];
        this.selectRows = rows;
    },
     //导出列表
    async downloadFile() {
      // utils.showLoading("正在生成中")
      let new_ids=""
      if((this.selectRows.checked==true && this.selectRows.records.length!= 0)||(this.selectRows.checked==false && this.selectRows.records.length!= 0)){
        //导出值用id|id形式拼接
        this.selectRows.records.forEach(item => {
          new_ids+='|'+item.id
        });
        if(new_ids!=''){
          new_ids=new_ids.substring(1)
        }
        let res = await this.RequestPost("export_list",{"ids":new_ids});
        if(res.code==0){
          utils.hideLoading()
            await utils.sleepMs(500);
            // let blob=new Blob([res.data],{type:'app/xml'})
            // utils.showTip("导出成功，在IM中查收");
            window.location.href = ACDN+res.data
        }else{
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":"导出异常",
          "title":"提示"});
        }
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请至少选择一项 ",
         "title":"提示"});
      }
      
    },
    async updateInfo(info) {
      
      utils.showLoading()
      let code = -1;
      let actionName = '';
      let tipText = '';
      let res = '';
      let postData = utils.cloneObj(info);
      let new_ids=""
      
      if (this.handleType==1) {
        if( this.selectRows.length != 0  &&  this.selectRows.records.length != 0){
          this.selectRows.records.forEach(item => {
            new_ids+='|'+item.id
          });
          if(new_ids!=''){
            new_ids=new_ids.substring(1)
          }
          actionName = 'download_items';
          tipText = '下载成功！'; 
          postData["ids"]=new_ids
          postData["file_type"]=info.file_type   
        }else{
          actionName = 'download_items';
          tipText = '下载成功！'; 
          postData["file_type"]=info.file_type
        }
      }else if(info.file_type==4){
        postData["batched"]=1
        delete postData["file_type"]
      }else if(info.file_type==5){
        postData["batched"]=0
        postData["file_type"]=3
      }
      if((postData["number_of_single"]<100 || postData["number_of_single"]>1000000)&&postData["export_mode"]==1){
        // alert("单次文件筛选数限制:1000<数量<100w")
        utils.hideLoading();
        utils.showSureModal({"modalContent":"限制:100<数量<100w"});
      }else{
        res = await this.RequestPost(actionName, postData);
        code = res.code;
        if (code == 0) {
          let aaa=ACDN+res.data
          //下载txt判断
            let index= res.data.lastIndexOf(".");//获取.的下标
            let ext = res.data.substr(index+1);//获取后缀txt
            let index2= res.data.lastIndexOf("/");//获取/的下标
            let ext2 = res.data.substr(index2+1,res.data.length);//获取/后的文件名
          if("txt".indexOf(ext.toLowerCase()) !== -1){
            this.exportData2(aaa,ext2)
          }else{
            window.open(ACDN+res.data)
          }
          utils.hideFormPage(this.formPopIndex);
          await utils.sleepMs(1000);
          this.selectRows = [];
          this.onSearchGetList();
          utils.showTip(tipText);
        }
        else{
          utils.showSureModal({"icon":require('../../assets/images/peach-svg/hongtan.svg'),
          "modalContent":res.data,
          "title":"提示"});
        }
        utils.hideLoading();
      }
    }, 
    //txt下载
    exportData2(url,name){
     const link = document.createElement("a");
      fetch(url)
      .then((res)=>res.blob())
      .then((blob)=>{
       link.href = URL.createObjectURL(blob)
       link.download = name
       document.body.appendChild(link)
       
       link.click()
        document.body.removeChild(link)
      })
     }
      ,
    //源文件下载
    async addSieveOpen(value){
      // utils.showLoading("正在生成中")
      
      let new_ids=""
      if(this.selectRows.checked==true && this.selectRows.records.length==1){
        this.addWarehouse(1,value)
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请选择一项 ",
         "title":"提示"});
      }
    },  
    //批量导出文件下载（去重）
    async addSieveOpen2(value){
      // utils.showLoading("正在生成中")
      let new_ids=""
      if((this.selectRows.checked==true && this.selectRows.records.length!= 0)||(this.selectRows.checked==false && this.selectRows.records.length!= 0)){
        this.addWarehouse2(1,value)
      }else{
         utils.showSureModal({"icon":require('../../assets/images/peach-svg/bluegth.svg'),
         "modalContent":"请至少选择一项 ",
         "title":"提示"});
      }
    },  
    onChangePageSize(page,pageSize){
      this.modal = true        
      this.searchData.page_index = page;
      this.searchData.page_size = pageSize;
      this.getList();
    },
    changeDate(){
      // this.searchTime.forEach((item,index)=>{
      //     let hour = item.split(":")[0]
      //     this.searchDate[index].setHours(hour);
      //     if(index==1){
      //       this.searchDate[index].setMinutes(59)
      //       this.searchDate[index].setSeconds(59)
      //     }
      //   })
      this.searchData.start = Date.parse(this.searchDate[0])/1000;
      this.searchData.end = Date.parse(this.searchDate[1])/1000+86400;
      this.onSearchGetList();
    },
    initDate(){
      let nowDay = ""
      let beginDay = nowDay;
      let endDay = nowDay;
      this.searchDate = [new Date(beginDay),new Date(endDay)];
      this.changeDate();
    },
    slotHeader(h) {
    //   return [h("div",{class:{"allCount":true},"style":{"margin-left":"10px"}})]
    },
    filterPartner(item){
      
      if (item.Id == -1) return true;
      if (this.searchData.searchBusinessId == -1 ) return true
        return item.BusinessId==this.searchData.searchBusinessId;
    },
    filterChannel(item){
      if(this.searchData.searcPartnerId == undefined) {
        this.searchData.searcPartnerId = -1
      }
      if(this.searchData.searchBusinessId == undefined) {
        this.searchData.searchBusinessId = -1
      }

      if (item.Id == -1) return true;
      if ( this.searchData.searchBusinessId == -1 && this.searchData.searcPartnerId == -1 ) return true
      if ( this.searchData.searchBusinessId == -1 && this.searchData.searcPartnerId != -1 && item.PartnerId==this.searchData.searcPartnerId ) return true
      if ( this.searchData.searchBusinessId != -1 && this.searchData.searcPartnerId != -1 && item.PartnerId==this.searchData.searcPartnerId ) return true
      if ( this.searchData.searchBusinessId != -1 && this.searchData.searcPartnerId == -1 && item.BusinessId==this.searchData.searchBusinessId ) return true 
    },
    async onSelectChange(label,value){
      this.format.number_of_single.labelHide = true;
       if(label=="export_mode"){
        
          if(value==1){
            this.format.number_of_single.labelHide = false;
          }
          // else{
          //   this.format.number_of_single.labelHide = true;
          // }
       }
    },
    updateData(updateData) {
      updateData.forEach((item) => {
        for(var i = 0; i<this.list.length; i++){
            if (this.list[i].id != item.id) {
                continue
            }
            this.list[i].status = item.status
            this.list[i].end_time=item.end_time
            this.list[i].elapsed_time=item.elapsed_time
            this.list[i].valid_number=item.valid_number
            this.list[i].points_consume_total=item.points_consume_total
            this.list[i].points_consume_account=item.points_consume_account
            this.list[i].points_consume_gift=item.points_consume_gift
        }
      })
    }
  },
  mounted() {
    bus.$on('update-sieve-list', this.updateData);   
    bus.$on('insvalid',data =>{
        this.list=data
      })
  },
  beforeDestroy() {
    bus.$off('update-sieve-list');
  },
};
</script>  